package com.youdoneed.news.news.web;

import com.youdoneed.base.application.AppException;
import com.youdoneed.base.common.JWTUtils;
import com.youdoneed.news.common.vo.ResultMessage;
import com.youdoneed.news.news.entity.CmfAuthors;
import com.youdoneed.news.news.service.CmfAuthorService;
import com.youdoneed.news.news.service.CmfPostsService;
import com.youdoneed.news.news.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.List;
import java.util.Map;

@SuppressWarnings("unchecked")
@RestController
@RequestMapping(value = "/posts", method = {RequestMethod.GET, RequestMethod.POST})
@Api(value = "新闻内容模块控制器", description = "新闻内容模块控制器")
public class CmfPostsController {

    private static final Logger logger = LoggerFactory.getLogger(CmfPostsController.class);

    @Autowired
    CmfPostsService cmfPostsService;
    @Autowired
    CmfAuthorService cmfAuthorService;

    /**
     * 获取好友浏览过的新闻列表
     *
     * @throws ParseException
     * @throws NumberFormatException
     * @author hexz
     * @date 2017.7.3
     */
    @RequestMapping(value = "/getReadPostsOfFriends", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "获取好友浏览过的新闻列表", value = "获取好友浏览过的新闻列表")
    public ResultMessage<List<CmfPostsListOfFriends>> getReadLogOfFriends(
            @ApiParam("页数") @RequestParam Integer offset,
            @ApiParam("条数") @RequestParam Integer limit,
            @RequestHeader(value = "Authorization") String token) throws NumberFormatException, ParseException {
        String userId = JWTUtils.getTokenUserId(token);
        logger.info("开始获取好友浏览历史" + userId);
        List<CmfPostsListOfFriends> readList = cmfPostsService.getReadPostsOfFriends(userId, offset, limit);
        return ResultMessage.newSuccess("获取好友浏览过的新闻列表成功").setData(readList);
    }

    /**
     * 根据id获取新闻详情，并记录浏览历史
     *
     * @author hexz
     * @date 2017.7.3
     */
    @RequestMapping(value = "/getPostDetailById", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "获取新闻详情,记录浏览历史", value = "获取新闻详情,记录浏览历史")
    public ResultMessage<CmfPostsDtlVo> getPostDetailById(
            @ApiParam(value = "客户端请求头附带参数") @RequestHeader(value = "Authorization") String token,
            @ApiParam("文章id") @RequestParam Long postId) {
        String userId = JWTUtils.getTokenUserId(token);
        logger.info("开始获取新闻详情" + userId + "," + postId);
        CmfPostsDtlVo postDetail = cmfPostsService.getPostDetailById(postId, userId);
        return ResultMessage.newSuccess("获取文章详情成功").setData(postDetail);
    }

    /**
     * 根据id获取新闻详情
     *
     * @return
     * @author hexz
     * @date 2017.7.3
     */
    @RequestMapping(value = "/getPostsDtlById", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "获取新闻详情", value = "获取新闻详情")
    public ResultMessage<CmfPostsDtlVo> getPostDtlById(@ApiParam("文章id") @RequestParam Long postId) {
        logger.info("开始获取新闻详情" + postId);
        //获取新闻详情
        CmfPostsDtlVo postDetail = cmfPostsService.getPostDetailById(postId, null);
        if (null == postDetail) {
            return ResultMessage.newFailure("未获取到文章详情信息");
        }
        //获取作者来源信息
        CmfAuthors authors = cmfAuthorService.getAuthorsOfPosts(Integer.valueOf(String.valueOf(postDetail.getAuthorId())));
        postDetail.setAuthors(authors);
        return ResultMessage.newSuccess("获取文章详情成功").setData(postDetail);
    }

    /**
     * 根据关键字搜索新闻
     *
     * @param keyWords
     * @return
     * @author hexz
     * @date 2017.7.3
     */
    @RequestMapping(value = "/getPostsByKeywords", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "根据关键字搜索新闻", value = "根据关键字搜索新闻")
    public ResultMessage<List<CmfPostsListVo>> getPostsByKeywords(
            @ApiParam("搜索的关键字") @RequestParam String keyWords,
            @ApiParam("展示条数") @RequestParam Integer pageSize,
            @ApiParam("最后一条新闻的时间") @RequestParam(required = false) Integer lastTime) {
        logger.info("根据关键字" + keyWords + "进行查询");
        List<CmfPostsListVo> postsListVo = cmfPostsService.getPostsByKeywords(keyWords, pageSize, lastTime);
        if (null == postsListVo || postsListVo.size() < 1) {
            return ResultMessage.newSuccess("根据关键字未搜索到新闻列表");
        }
        return ResultMessage.newSuccess("根据关键字搜索成功").setData(postsListVo);
    }

    /**
     * 根据栏目获取新闻列表
     *
     * @return
     * @author hexz
     * @date 2017.7.3
     */
    @RequestMapping(value = "/getPostsList", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "根据新闻栏目获取新闻列表", value = "根据新闻栏目获取新闻列表")
    public ResultMessage<List<CmfPostsListVo>> getPostsList(
            @ApiParam("每页显示新闻条数") @RequestParam Integer pageSize,
            @ApiParam("导航id") @RequestParam Integer navId,
            @ApiParam("时间节点,格式 2017-07-06 00:00:00") @RequestParam(required = false) String lastTime,
            @ApiParam(value = "客户端请求头附带参数") @RequestHeader(value = "Authorization") String token) {
        String userId = JWTUtils.getTokenUserId(token);
        logger.info("开始增量获取新闻列表");
        //根据关系列表获取新闻列表
        List<CmfPostsListVo> postsList = cmfPostsService.getnewsByTermId(navId, pageSize, userId);
        if (null == postsList || postsList.size() < 1) {
            return ResultMessage.newSuccess("未获取到新闻列表");
        }
        return ResultMessage.newSuccess("获取新闻列表成功").setData(postsList);
    }
//    /**
//     * 获取新闻列表及缓存新闻最新评论数
//     *
//     * @return
//     * @author hexz
//     * @date 2017.10.23
//     */
//    @RequestMapping(value = "/getPostsListAndCommentCount", method = {RequestMethod.GET, RequestMethod.POST})
//    @ApiOperation(notes = "获取新闻列表及缓存新闻最新评论数", value = "获取新闻列表及缓存新闻最新评论数")
//    public ResultMessage<CmfNewsAndCommentCount> getPostsListAndCommentCount(
//            @ApiParam("每页显示新闻条数") @RequestParam Integer pageSize,
//            @ApiParam("导航id") @RequestParam Integer navId,
//            @ApiParam("时间节点,格式 2017-07-06 00:00:00") @RequestParam(required = false) String lastTime,
//            @ApiParam("缓存ID数组") @RequestParam String ids,
//            @ApiParam(value = "客户端请求头附带参数") @RequestHeader(value = "Authorization") String token) {
//        String userId = JWTUtils.getTokenUserId(token);
//        logger.info("开始增量获取新闻列表");
//        //根据关系列表获取新闻列表
//        CmfNewsAndCommentCount postsList = cmfPostsService.getPostsListAndCommentCount(navId, pageSize, lastTime, userId,ids);
//        if (null == postsList.getPostsListVos() || postsList.getPostsListVos().size() < 1) {
//            return ResultMessage.newSuccess("未获取到新闻列表");
//        }
//        return ResultMessage.newSuccess("获取新闻列表成功").setData(postsList);
//    }

    /**
     * 获取热评新闻列表
     *
     * @param lastTime
     * @return
     * @author hexz
     */
    @RequestMapping(value = "/getHotCommentNews", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "获取热评新闻列表", value = "获取热评新闻列表")
    public ResultMessage<List<CmfPostsListVo>> getHotCommentNews(
            @ApiParam("每页显示新闻条数") @RequestParam Integer pageSize,
            @ApiParam("时间节点,格式 2017-07-06 00:00:00") @RequestParam(required = false) String lastTime,
            @ApiParam(value = "客户端请求头附带参数") @RequestHeader(value = "Authorization") String token) {
        logger.info("开始查询热评新闻");
        String userId = JWTUtils.getTokenUserId(token);
        return ResultMessage.newSuccess("获取热评新闻列表成功").setData(cmfPostsService.getHotCommentNews(pageSize, lastTime, userId));
    }

    /**
     * 首页获取用户关注的新闻列表
     *
     * @param userId
     * @return
     * @author hexz
     */
    @RequestMapping(value = "/getNewsForHomePage", method = {RequestMethod.POST, RequestMethod.GET})
    @ApiOperation(notes = "首页获取用户关注的新闻列表", value = "首页获取用户关注的新闻列表")
    public ResultMessage<List<CmfPostsListVo>> getNewsForHomePage(
            @RequestParam(required = false) Integer beforeDeadTime,
            @RequestParam(required = false) Integer lastDeadtime,
            @ApiParam("用户id") @RequestParam String userId) {
        if (null != beforeDeadTime) {
            logger.info("beforeDeadTime:" + beforeDeadTime);
        }
        logger.info("开始查询" + userId + beforeDeadTime + lastDeadtime);
        List<CmfPostsListVo> postsListVos = cmfPostsService.getNewsForHomePage(beforeDeadTime, lastDeadtime, userId);
        if (null == postsListVos || postsListVos.size() < 1) {
            return ResultMessage.newSuccess("未获取到新的新闻");
        }
        logger.info("=============" + postsListVos.size());
        return ResultMessage.newSuccess("获取新闻列表成功").setData(postsListVos);
    }

    /**
     * 通过id列表获取新闻列表
     * @param ids
     * @return
     */
    @RequestMapping(value = "/getNewsByIds", method = {RequestMethod.POST, RequestMethod.GET})
    @ApiOperation(notes = "通过id列表获取新闻列表", value = "通过id列表获取新闻列表")
    public  ResultMessage<List<CmfPostsListVo>> getNewsByIds(@RequestBody List<Long> ids){
        List<CmfPostsListVo> listCmfPostsListVo = cmfPostsService.getNewsByIds(ids);
        return ResultMessage.newSuccess("获取新闻列表成功").setData(listCmfPostsListVo);
    }

    /**
     * 根据关键字搜索视频
     *
     * @param keyWords
     * @return
     * @author hexz
     */
    @RequestMapping(value = "/searchForVideos", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "搜索新闻中的视频列表", value = "搜索新闻中的视频列表")
    public ResultMessage<List<CmfPostsListVo>> searchForVideos(
            @ApiParam("关键字") @RequestParam(required = true) String keyWords,
            @ApiParam("当前页数") @RequestParam Integer offset,
            @ApiParam("每页显示新闻条数") @RequestParam Integer limit,
            @RequestHeader(value = "Authorization") String token) {
        String userId = JWTUtils.getTokenUserId(token);
        logger.info("开始搜索视频" + keyWords);
        List<CmfPostsListVo> videoList = cmfPostsService.searchForVideos(userId, keyWords, offset, limit);
        return ResultMessage.newSuccess("搜索视频成功").setData(videoList);
    }

    /**
     * 更新新闻评论数
     *
     * @param postsId
     * @return
     * @author hexz
     */
    @RequestMapping(value = "updateCommentCount", method = RequestMethod.POST)
    @ApiOperation(notes = "更新新闻评论数", value = "更新新闻评论数")
    public ResultMessage<Integer> updateCommentCount(
            @ApiParam("新闻唯一标识") @RequestParam Long postsId,
            @ApiParam("操作类型0,添加评论;1,删除评论") @RequestParam String updateType) {
        cmfPostsService.updateCommentCount(postsId, updateType);
        return ResultMessage.newSuccess("更新评论数成功");
    }

    /**
     * 更新新闻点赞数
     *
     * @param postsId
     * @return
     * @author hexz
     */
    @RequestMapping(value = "updatePostLikes", method = RequestMethod.POST)
    @ApiOperation(notes = "更新新闻点赞数", value = "更新新闻点赞数")
    public ResultMessage<Integer> updatePostLikes(
            @ApiParam("新闻唯一标识") @RequestParam Long postsId,
            @ApiParam("0,点赞;1,取消点赞") @RequestParam String likesType) {
        cmfPostsService.updatePostLikes(postsId, likesType);
        return ResultMessage.newSuccess("更新点赞数成功");
    }

    /**
     * 获取趣视频
     *
     * @param navId
     * @return
     * @author hexz
     */
    @RequestMapping(value = "getJokeVideos", method = RequestMethod.POST)
    @ApiOperation(notes = "获取趣视频", value = "获取趣视频")
    public ResultMessage<List<CmfVideoListVo>> getJokeVideos(
            @ApiParam("当前页数") @RequestParam Integer offset,
            @ApiParam("每页显示新闻条数") @RequestParam Integer limit,
            @ApiParam("对应栏目") @RequestParam Integer navId,
            @ApiParam("关键字") @RequestParam(required = false) String keywords) {
        logger.info("开始获取趣视频列表");
        List<CmfVideoListVo> videoList = cmfPostsService.getJokeVideoList(navId, offset, limit, keywords);
        return ResultMessage.newSuccess("获取视频列表成功").setData(videoList);
    }

    /**
     * 首页获取趣闻推荐
     *
     * @param pageSize
     * @return
     * @author hexz
     */
    @RequestMapping(value = "/getJokes", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "首页趣闻推荐", value = "首页趣闻推荐")
    public ResultMessage<Map<String, Object>> getJokes(
            @ApiParam("条数，不传默认取一条") @RequestParam(required = false) Integer pageSize,
            @ApiParam("时间节点，2017-7-27 00:00:00") @RequestParam(required = false) String lastTime,
            @RequestHeader(value = "Authorization") String token) {
        logger.info("开始获取趣闻推荐");
        pageSize = (null == pageSize) ? 1 : pageSize;
        String userId = JWTUtils.getTokenUserId(token);
        return ResultMessage.newSuccess("获取趣闻推荐成功").setData(cmfPostsService.getJokes(pageSize, lastTime, userId));
    }

    /**
     * 首页获取热评新闻
     *
     * @param pageSize
     * @return
     * @author hexz
     */
    @RequestMapping(value = "/getHotNewsForIndex", method = {RequestMethod.POST, RequestMethod.GET})
    @ApiOperation(notes = "首页热评新闻", value = "首页热评新闻")
    public ResultMessage<Map<String, Object>> getNewsForHomePage(
            @ApiParam("获取条数,不传默认3条") @RequestParam(required = false) Integer pageSize,
            @ApiParam("时间节点，2017-7-26 00:00:00") @RequestParam(required = false) String lastTime,
            @RequestHeader(value = "Authorization") String token) {
        logger.info("开始查询热评新闻");
        String userId = JWTUtils.getTokenUserId(token);
        pageSize = (null == pageSize) ? 3 : pageSize;
        return ResultMessage.newSuccess("获取新闻成功").setData(cmfPostsService.getHotNewsForHomePage(pageSize, userId));
    }

    /**
     * 新闻推荐
     *
     * @param token
     * @param pageSize
     * @return
     * @author hexz
     */
    @RequestMapping(value = "/newsRecommended", method = {RequestMethod.POST, RequestMethod.GET})
    @ApiOperation(notes = "获取推荐新闻", value = "获取推荐新闻")
    public ResultMessage<List<CmfPostsListVo>> newsRecommended(
            @RequestHeader(value = "Authorization") String token,
            @ApiParam("指定条数") @RequestParam Integer pageSize) {
        String userId = JWTUtils.getTokenUserId(token);
        return ResultMessage.newSuccess("获取推荐新闻成功").setData(cmfPostsService.getRecommendedNews(userId, pageSize));
    }

//    /**
//     * 初始用户新闻推荐权值
//     *
//     * @param gender
//     * @param bornDate
//     * @return
//     * @author hexz
//     */
//    @RequestMapping(value = "/initUserWeight", method = {RequestMethod.POST, RequestMethod.GET})
//    @ApiOperation(notes = "初始化用户权值", value = "初始化用户权值")
//    public ResultMessage<Integer> initUserWeight(
//            @ApiParam("用户ID") @RequestParam String userId,
//            @ApiParam("性别") @RequestParam(required = false) Integer gender,
//            @ApiParam("出生日期") @RequestParam(required = false) Long bornDate) {
//        cmfPostsService.initUserWeight(userId, gender, bornDate);
//        return ResultMessage.newSuccess("初始化权值成功");
//    }

    /**
     * 获取视频列表
     *
     * @param token
     * @param postsId
     * @param pageSize
     * @return
     * @author hexz
     */
    @RequestMapping(value = "/getRelationVideos", method = {RequestMethod.POST, RequestMethod.GET})
    @ApiOperation(notes = "获取相关联的视频列表", value = "获取相关联的视频列表")
    public ResultMessage<List<CmfVideoListVo>> getRelationVideos(
            @RequestHeader(value = "Authorization") String token,
            @ApiParam("视频id") @RequestParam Long postsId,
            @ApiParam("指定条数") @RequestParam Integer pageSize,
            @ApiParam("新闻类型1-视频，2-其他") @RequestParam Integer type) {
        String userId = JWTUtils.getTokenUserId(token);
        List<CmfPostsListVo> relateNews = cmfPostsService.getRelationNews(postsId, pageSize, userId, type);
        if (null == relateNews || relateNews.size() < 1) {
            return ResultMessage.newSuccess("暂无相关新闻").setData(relateNews);
        }
        return ResultMessage.newSuccess("获取相关联的新闻列表成功").setData(relateNews);
    }

    /**
     * 根据ID获取新闻列表，分享用
     *
     * @param postId
     * @return
     */
    @RequestMapping(value = "/getPostsListById", method = {RequestMethod.POST, RequestMethod.GET})
    @ApiOperation(notes = "根据ID获取新闻列表", value = "根据ID获取新闻列表")
    public ResultMessage<CmfPostsListVo> getPostsListById(
            @ApiParam("新闻ID") @RequestParam Long postId) {
        return ResultMessage.newSuccess("获取新闻列表成功").setData(cmfPostsService.getPostsListById(postId));

    }

    /**
     * 获取热闻列表
     *
     * @param offset
     * @param limit
     * @return
     */
    @RequestMapping(value = "/getImportantNews", method = {RequestMethod.POST, RequestMethod.GET})
    @ApiOperation(notes = "获取热闻列表", value = "获取热闻列表")
    public ResultMessage<CmfPostsListVo> getImportantNews(
            @ApiParam("当前页数") @RequestParam Integer offset,
            @ApiParam("条数") @RequestParam Integer limit,
            @RequestHeader(value = "Authorization") String token) {
        String userId = JWTUtils.getTokenUserId(token);
        return ResultMessage.newSuccess("获取热闻列表成功").setData(
                cmfPostsService.getImportantNews(offset, limit, userId));
    }

    /**
     * 获取热门视频(视频子栏目中)
     *
     * @param count
     * @param token
     * @return
     */
    @RequestMapping(value = "/getHotVideos", method = {RequestMethod.POST, RequestMethod.GET})
    @ApiOperation(notes = "获取热门视频", value = "获取热门视频")
    public ResultMessage<CmfPostsListVo> getHotVideos(
            @ApiParam("条数") @RequestParam Integer count,
            @RequestHeader(value = "Authorization") String token) {
        String userId = JWTUtils.getTokenUserId(token);
        return ResultMessage.newSuccess("获取热门视频").setData(
                cmfPostsService.getHotVideos(userId, count));
    }

    /**
     * 获取推荐视频
     *
     * @param offset
     * @param limit
     * @return
     */
    @RequestMapping(value = "getRecommendedVideos")
    @ApiOperation(notes = "获取推荐视频", value = "获取推荐视频")
    public ResultMessage<CmfPostsListVo> getRecommendedVideos(
            @ApiParam("当前页数") @RequestParam Integer offset,
            @ApiParam("条数") @RequestParam Integer limit) {
        if (offset == null || limit == null) {
            throw new AppException("分页参数不能为空");
        }
        return ResultMessage.newSuccess("获取推荐趣视频成功").setData(
                cmfPostsService.getRecommendedVideos(offset, limit));
    }

    /**
     * 获取最新评论数(缓存新闻评论数更新)
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = "reloadCommentCount")
    @ApiOperation(notes = "获取最新评论数", value = "获取最新评论数")
    public ResultMessage<List<CmfCommentCountVo>> reloadCommentCount(
            @ApiParam("id数组") @RequestParam String ids) {
        return ResultMessage.newSuccess("获取最新评论数成功").setData(
                cmfPostsService.reloadCommentCount(ids));
    }

    /**
     * PC后台根据标题关键字检索新闻
     *
     * @param keywords
     * @param lastTime
     * @param limit
     * @return
     */
    @RequestMapping(value = "findNewsByKeywords")
    @ApiOperation(notes = "PC后台根据标题关键字检索新闻", value = "PC后台根据标题关键字检索新闻")
    public ResultMessage<List<CmfFindNewsVo>> findNewsByKeywords(
            @ApiParam("关键字") @RequestParam String keywords,
            @ApiParam("最后一条新闻时间") @RequestParam(required = false) Integer lastTime,
            @ApiParam("条数") @RequestParam Integer limit) {
        return ResultMessage.newSuccess("获取新闻成功").setData(
                cmfPostsService.findNewsByKeywords(lastTime, limit, keywords));
    }



}